const express = require("express");
const router = express.Router();
const Db = require("../../utils/db");
const createSql = require("../../utils/Create_SQL");
const { errorCode, successCode, config } = require('../../config/config');
const utils = require("../../utils/utils.js")

const typeToMytype = [
    {
        type: "tinyint",
        mytype: "Boolean",
        formType: {
            type: 'switch'
        }
    },
    {
        type: "datetime",
        mytype: "Date",
        formType: {
            type: "date",
            props: {
                'value-format': 'yyyy-MM-dd HH:mm:ss'
            }
        }
    },
    {
        type: "int",
        mytype: "Number",
        formType: {
            type: "number"
        }
    },
    {
        type: "varchar",
        mytype: "String",
        formType: {
            type: "input"
        }
    },
    {
        type: "text",
        mytype: "String",
        formType: {
            type: "input",
            props: {
                type: "textarea",
                rows: 4,
                autosize: true
            }
        }
    },
    {
        type: "longtext",
        mytype: "String",
        formType: {
            type: "input",
            props: {
                type: "textarea",
                rows: 4,
                autosize: true
            }
        }
    },
    {
        type: "double",
        mytype: "Number",
        formType: {
            type: "number",
            props: {
                precision: 2
            }
        }
    },
    {
        type: "float",
        mytype: "Number",
        formType: {
            type: "number",
            precision: 4
        }
    },
    {
        type: "decimal",
        mytype: "Number",
        formType: {
            type: "number"
        }
    },
    {
        type: "bigint",
        mytype: "Number",
        formType: {
            type: "input",
            props: {
                type: "number"
            }
        }
    }
]

/**
 * @swagger
 * /api/v2/createFile/admin:
 *    get:
 *      tags:
 *      - 生成文件
 *      summary: 生成开发文件-后台
 *      produces:
 *      - application/json
 *      parameters:
 *        - name: tableName
 *          description: 表名称
 *          in: query
 *          required: true
 *          type: string
 *      responses:
 *        200:
 *         description: successful operation
 * */
router.get("/admin", async function (req, res) {
    let { tableName, searchData } = req.query;
    let sql = createSql.customAll(`SHOW FULL COLUMNS FROM ${tableName}`).sql;
    let result = await Db.query(sql, res);
    if (result.length == 0) {
        return res.json({
            code: 400,
            msg: "没有数据"
        })
    }
    let checkJson = {};
    let tableJson = [];
    let formJson = {
        formProps: {
            labelWidth: "120px"
        },
        formItem: []
    }
    // 需要排除的关键字
    const excludeKey = ["id", "ID", "createtime", "createdtime", "updatetime", "addtime", "is_del", "updateTime", "addTime", 'create_user', 'createByUser'];
    result.forEach(element => {
        let type = "";
        let formType = "";
        typeToMytype.forEach(item => {
            if (item.type == element.Type.split("(")[0]) {
                type = item.mytype;
                formType = item.formType;
            }
        })
        if (excludeKey.indexOf(element.Field) < 0) {
            checkJson[element.Field] = {
                type: type,
                desc: element.Comment || element.Field
            }
            element.Null == "NO" ? checkJson[element.Field].message = `${element.Comment || element.Field}不能为空` : "";
            checkJson[element.Field].required = element.Null == "NO" ? true : false;
            let formItem = {
                label: element.Comment || element.Field,
                ...formType,
                key: element.Field
            }
            if (element.Field == "ID" || element.Field == "id") {
                formItem.isHidden = true
            }
            if (element.Null == "NO") {
                formItem.rules = [
                    {
                        required: true,
                        message: checkJson[element.Field].message,
                        trigger: 'blur'
                    }
                ]
            }
            formJson.formItem.push(formItem)
        }


        tableJson.push({
            label: element.Comment || element.Field,
            key: element.Field
        })
    });

    // 下划线后面的字母大写
    let tableNameUpper = tableName.replace(/_(\w)/g, function (all, letter) {
        return letter.toUpperCase();
    });
    // 首字母大写
    tableNameUpper = tableNameUpper.replace(/^(\w)/, function (all, letter) {
        return letter.toUpperCase();
    });

    // 生成查询函数
    let searchStr = "";
    searchData = searchData ? searchData : '';
    let searchDatas = searchData.split(",");
    let whereStr = "";
    let andStr = ""
    searchData && searchDatas.forEach((element , index) => {
        if(index == 0){
            whereStr += ` \${${element} ? "${element} like '%" + ${element} + "%' and " : ''}`
        }else{
            andStr += `.and(\`\${${element} ? "${element} like '%" + ${element} + "%'" : ''} \`)\n\t`
        }
    });
    searchStr = `
    let {  pageSize , page, ${searchData} } = req.query;
    pageSize = pageSize || 10;
    page = page || 1;
    let sql = createSqlv2().select('${tableName}.* , user_admin.user_name as username').from("${tableName}")
    .leftJoin("user_admin")
    .on('${tableName}.create_user = user_admin.ID')
    ${whereStr ? `.where(\`${whereStr} and is_del = 0\`)` : `.where(\`${tableName}.is_del = 0\`)`}
    ${andStr}
    .limit(\`\${pageSize * (page - 1)}, \${pageSize}\`)
    .build();
    let countSql = createSqlv2().select("count(*) as count").from("${tableName}")
    ${whereStr ? `.where(\`${whereStr} and is_del = 0\`)` : `.where(\`${tableName}.is_del = 0\`)`}
    ${andStr}
    .build();
`
    /**生成函数*/
    let searchResult = `
router.get("/get${tableNameUpper}", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    ${searchStr}
    let data = await Db.query(sql, res);
    if (data.code) return;
    let countData = await Db.query(countSql);
    if (countData.code) return;
    return res.json({
        ...successCode[200],
        data: {
            data: data,
            count: countData[0].count
        }
    })
})`;

    // 生成删除语句
    let deleteStr = `
router.post("/delete${tableNameUpper}", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code != 200) return;
    let { ID } = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let sql = createSql.select().from("${tableName}").where(\`ID = '\${ID}'\`).build();
    let data = await Db.query(sql, res);
    if (data.code) return;
    if (!data.length) {
        return res.json({
            ...errorCode[10008],
            message: "没有找到该数据"
        })
    }
    data = {
        updatetime: utils.getTime(),
        create_user: isLogin.data.ID,
        is_del: 1
    }
    sql = createSqlv2().update("${tableName}").set(data).where(\`ID = '\${ID}'\`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})
`

    // 添加函数
    const addStr = `
router.post("/add${tableNameUpper}", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    let data = utils.checkData(req.body, objectCheck.${tableNameUpper}_add);
    if (data.code > 200) return res.json(data);
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.createdtime = utils.getTime();
    data.ID = utils.getUuid();
    let sql = "";
    sql = createSqlv2().insert("${tableName}").value(data).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
})
`

    const updateStr = `
router.post("/update${tableNameUpper}", async (req, res) => {
    let isLogin = {};
    try {
        isLogin = await utils.isLogin(req, res);
    } catch (error) {
        isLogin = error;
    }
    if (isLogin.code > 200) return;
    const { ID , is_show} = req.body;
    if (!ID) {
        return res.json({
            ...errorCode[10003]
        })
    }
    let data = {};
    let sql = "";
    data = utils.checkData(req.body, objectCheck.${tableNameUpper}_add);
    if (data.code > 200)  return res.json(data)
    data = data.data;
    data.create_user = isLogin.data.ID;
    data.updatetime = utils.getTime();
    sql = createSqlv2().update("${tableName}").set(data).where(\`ID = '\${ID}'\`).build();
    let result = await Db.query(sql, res);
    if (result.code) return;
    return res.json({
        ...successCode[200]
    })
});
    `

    return res.json({
        code: 200,
        msg: tableName,
        data: {
            checkJson: checkJson,
            tableJson: tableJson,
            formJson: formJson,
            searchResult: searchResult,
            deleteStr: deleteStr,
            addStr: addStr,
            updateStr: updateStr,
            tableNameUpper: tableNameUpper
        }
    })
});



module.exports = router;